# 通过ip请求淘宝的一个接口获取到省份和运营商
# - 接口：https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=要查询的ip地址
# - 每一行变成这种形式保存到文件
# - 格式：ip,中国,湖南,电信

import requests
import json

def getip(ip:str,filename:str):
    # 发送请求
    x = requests.get('https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip='+ip)
    # 返回网页内容并转换成字典对象
    name_dict = json.loads(x.text)
    with open(filename, "w", encoding="utf-8") as fp:
        try:
            fp.seek(0, 2)
            for key,value in name_dict.items():
                if key == 'data':
                    fp.write("Ip地址"+":"+value['queryIp']+"\n")
                    fp.write("国家" + ":" + value['country'] + "\n")
                    fp.write("省份" + ":" + value['region'] + "\n")
                    fp.write("城市" + ":" + value['city'] + "\n")
                    fp.write("运营商" + ":" + value['isp'] + "\n")
        except Exception as ex:
            print("出错啦!")
getip('175.0.150.8', "test2.txt")